<template>
  <div>
    <el-card>
      <template #header>
        <div>
          <el-form :model="form" inline>
            <el-row>
              <el-form-item label="企业" label-width="70px">
                <el-select v-model="form.keyWord" filterable clearable placeholder="请选择公司名称" @change="columnChange" style="width: 170px">
                  <el-option v-for="item in options" :key="item.enterpriseId" :label="item.cmpName"
                    :value="item.enterpriseCode" />
                  <template #prefix>
                    <el-icon class="el-input__icon">
                      <search />
                    </el-icon>
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item label="数据编码">
                <el-input v-model="form.code" style="width: 170px" placeholder="请输入数据编码" clearable @change="columnChange">
                  <template #prefix>
                    <el-icon class="el-input__icon">
                      <search />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="数据统计时间">
                <el-date-picker v-model="form.date" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
                  :default-time="defaultTime2" @change="columnChange" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="是否上报">
                <el-select placeholder="请选择是否上报" v-model="form.dataIndex" filterable clearable @change="columnChange" style="width: 170px">
                  <el-option key="1" label="已上报" value="1" />
                  <el-option key="0" label="未上报" value="0" />
                  <template #prefix>
                    <el-icon class="el-input__icon">
                      <search />
                    </el-icon>
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item label="数据上报时间">
                  <el-date-picker
                    v-model="dateSelect"
                    type="date"
                    placeholder="选择日期" @change="dateChange()">
                  </el-date-picker>
                  <el-select v-model="form.update" placeholder="请选择数据上报时间段" style="width: 200px" clearable filterable @change="dateChange()">
                      <el-option v-for="option in dateList" :key="option.id" :label="option.name" :value="option.id"></el-option>
                  </el-select>
              </el-form-item> 
              <el-form-item>
                <el-button type="primary" @click="uploadBatchBtn()" :disabled="selectChangeList.length<=0">批量上报</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="danger" @click="deleteBatchBtn()" :disabled="selectChangeList.length<=0">批量删除</el-button>
              </el-form-item>
            </el-row>
          </el-form>

          <!-- <div>
            <el-button @click="addRow" size="small" type="primary"
              >添加</el-button
            >
            <el-button @click="getList" size="small" type="success"
              >查询</el-button
            >
            <el-button size="small">重置</el-button>
          </div> -->
        </div>
      </template>
      <el-table ref="enterpriseRef" :data="tableData" style="width: 100%; max-height: 61vh; height: 61vh " :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}"
      table-layout="auto" v-loading="loading" @sort-change="stateDateSort" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" :selectable="selectTable"/>
        <el-table-column fixed prop="enterName" label="公司名称" width="220" show-overflow-tooltip/>
        <el-table-column fixed prop="collectitemName" label="名称" width="220" />
        <el-table-column fixed prop="convertRationUnit" label="单位" width="150" />
        <el-table-column prop="dataCode" label="上报数据项编码" width="150"/>
        <el-table-column prop="dataValue" label="上传数据" width="80" />
        <el-table-column prop="convertRation" label="折标系数" width="80" />
        <el-table-column prop="dataIndex" label="端系统记录索引" width="140">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.dataIndex!=''">已上报</el-tag>
            <el-tag type="warning" v-if="scope.row.dataIndex==''">未上报</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="100" show-overflow-tooltip/>
        <el-table-column prop="statDate" label="数据统计时间" width="180" sortable="custom" />
        <el-table-column prop="uploadDate" label="数据上报时间" width="180" sortable="custom" />
        <el-table-column fixed="right" label="操作" min-width="200px" v-if="visible">
          <template #default="scope">
            <template v-if="scope.row.dataIndex != ''">
              <el-button link disabled type="primary" size="small" @click="updata(scope.$index, scope.row)">上报</el-button>
              <el-button link disabled type="primary" size="small"
                @click="rowChange(scope.$index, scope.row)">编辑</el-button>
            </template>
            <template v-else>
              <el-button link type="danger" size="small" @click="deleteBtn(scope.row.dataId)">删除</el-button>
              <el-button link type="primary" size="small" @click="updata(scope.$index, scope.row)">上报</el-button>
              <el-button link type="primary" size="small" @click="rowChange(scope.$index, scope.row)">编辑</el-button>
            </template>
            <el-button link type="primary" size="small" @click="handleClick(scope.$index, scope.row)">日志</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="card-footer">
        <el-pagination layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10,20,30,40,50,100,500]"
          background v-model:page-size="pagination.size"
          v-model:current-page="pagination.page" :total="pagination.total" @size-change="sizeChange"
          @current-change="pageChange" class="pagination" />
      </div>
      <!-- 修改信息对话框 -->
      <el-dialog v-model="dialogFormVisible" title="Shipping address">
        <el-form :model="form">
          <el-form-item label="Promotion name" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="Zones" :label-width="formLabelWidth">
            <el-select v-model="form.region" placeholder="Please select a zone">
              <el-option label="Zone No.1" value="shanghai" />
              <el-option label="Zone No.2" value="beijing" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">Cancel</el-button>
            <el-button type="primary" @click="dialogFormVisible = false">
              Confirm
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
    <LogInfo></LogInfo>
    <EditForm></EditForm>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import {  getNameList, eneryUpload,eneryUploadBatch } from "@/api/enterprise";
import { get,logicDelete,logicDeleteBatch} from "@/api/enterpriseEnergyList";
import { ElMessage,ElMessageBox } from "element-plus";
import { formatDateTime } from "@/utils";
import {getUserInfo} from "@/api/admin";
import LogInfo from "./dialogWithLogInfo/index.vue";
import EditForm from "./dialogWithForm/index.vue";
import mitts from "@/utils/bus.js";

const shortcuts = [
  {
    text: "Today",
    value: new Date(),
  },
  {
    text: "Yesterday",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: "A week ago",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];
//定义日期  日期不固定
const dateSelect=ref();
//提供固定时间段筛选
const dateList = ref([
  { id: "1", name: "10:00~12:00" },
  { id: "2", name: "14:00~16:00" },
  { id: "3", name: "16:00~18:00" },
]);
let defaultTime2 = [];
const form = reactive({
  keyWord: "",
  code: "",
  date: "",
  dataIndex: "",
  update: ""
});
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});
const condition = {
  column: "",
  type: "",
  value: "",
};
const options = ref([]);
const conditions = ref([]);
const dialogFormVisible = ref(false);
const tableData = ref([]);
const loading = ref(true);
const userRole=ref(String);
//控制操作列显隐的变量
const visible=ref(true);
//定义数组  存放选中的数据行
const selectChangeList=ref([]);
//多选框被点击时触发
const handleSelectionChange=(row)=>{
  selectChangeList.value=row
  console.log(selectChangeList.value)
}

const rowChange = (index, row) => {
  mitts.emit("editDialog", row);
};

//获取当前用户登录信息
const getUserRole=()=>{
  getUserInfo().then((res)=>{
    userRole.value=res.data.roleId;
  })
  console.log(userRole)
  if(userRole.value=="1"){
    visible.value=false;
  }
}
//定义方法 控制表格复选框是否禁选
const selectTable=(row,index)=>{
  if(row.dataIndex==""){
    return true;
  }else{
    return false;
  }
}
const getList = () => {
  loading.value = true;
  let datas = {
    pageNum: pagination.page,
    pageSize: pagination.size,
    condition: JSON.stringify(conditions.value),
  };
  get(datas)
    .then((res) => {
      //获取到信息
      tableData.value = res.data.records;
      pagination.size = res.data.pageSize;
      pagination.page = res.data.currentPage;
      pagination.total = res.data.total;
      doEnterName();
      loading.value = false;
    })
    .catch((msg) => {
      //获取出错
    });
};
mitts.on("editSuccess", (e) => {
  if (e) {
    doDataList();
  }
});

const handleClick = (index, rowData) => {
  mitts.emit("dataId", rowData);
  mitts.emit("visible", true);
};

/**
 * 页数据总数改变
 */
const sizeChange = (value) => {
  pagination.size = value;
  pagination.page = 1;
  getList();
};
/**
 * 页总数改变
 */
const pageChange = (value) => {
  pagination.page = value;
  getList();
};

//要么同时为空，要么同时不为空 触发
const dateChange=()=>{
  if(form.update!="" && dateSelect.value!=null){
    columnChange()
  }
  if(form.update=="" && dateSelect.value==null){
    columnChange()
  }
}
//日期拼接
const dateSplit=(hours)=>{
      var year = dateSelect.value.getFullYear(); // 年
      var month = (dateSelect.value.getMonth() + 1).toString().padStart(2, '0'); // 月
      var date = dateSelect.value.getDate().toString().padStart(2, '0'); // 日
      var hour = hours<10? "0"+hours:hours;
      return (year+"-"+month+"-"+date+" "+hour+":"+"00"+":"+"00")
}

const cloumnIndex = () => {
  let condi = [];
  let temp = {};
  var time1;
  var time2;
  if (form.keyWord != "" && form.keyWord != undefined) {
    temp = {
      column: "enterpriseCode",
      type: "eq",
      value: form.keyWord,
    };
    condi.push(temp);
  }
  if (form.code != "" && form.code != undefined) {
    temp = {
      column: "dataCode",
      type: "eq",
      value: form.code,
    };
    condi.push(temp);
  }
  if (form.date != "" && form.date != undefined) {
    temp = {
      column: "statDate",
      type: "ge",
      value: formatDateTime(form.date[0], "yyyy-MM-dd HH:mm:ss"),
    };
    condi.push(temp);
    temp = {
      column: "statDate",
      type: "le",
      value: formatDateTime(form.date[1], "yyyy-MM-dd HH:mm:ss"),
    };
    condi.push(temp);
  }
  if (form.update != "" && form.update != undefined) {
    // var nowDate=new Date(new Date().getTime());   获取当前时间
    if(form.update==="1"){
      time1=dateSplit(10);
      time2=dateSplit(12);
      console.log(time1);
      console.log(time2);
      temp={
        column:"uploadDate",
        type:"ge",
        value:time1
      };
      condi.push(temp);
      temp={
        column:"uploadDate",
        type:"le",
        value:time2
      }
      condi.push(temp);
    }else if(form.update==="2"){
      time1=dateSplit(14);
      time2=dateSplit(16);
      console.log(time1);
      console.log(time2);
      temp={
        column:"uploadDate",
        type:"ge",
        value:time1
      };
      condi.push(temp);
      temp={
        column:"uploadDate",
        type:"le",
        value:time2
      }
      condi.push(temp);
    }else{
      time1=dateSplit(16);
      time2=dateSplit(18);
      console.log(time1);
      console.log(time2);
      temp={
        column:"uploadDate",
        type:"ge",
        value:time1
      };
      condi.push(temp);
      temp={
        column:"uploadDate",
        type:"le",
        value:time2
      }
      condi.push(temp);
    }
    // temp = {
    //   column: "uploadDate",
    //   type: "ge",
    //   value: formatDateTime(form.update[0], "yyyy-MM-dd HH:mm:ss"),
    // };
    // condi.push(temp);
    // temp = {
    //   column: "uploadDate",
    //   type: "le",
    //   value: formatDateTime(form.update[1], "yyyy-MM-dd HH:mm:ss"),
    // };
    // condi.push(temp);
  }
  if (form.dataIndex != "" && form.dataIndex != undefined) {
    switch (form.dataIndex) {
      case "1":
        temp = {
          column: "dataIndex",
          type: "ne",
          value: "",
        };
        break;
      case "0":
        temp = {
          column: "dataIndex",
          type: "eq",
          value: "",
        };
        break;

    }
    condi.push(temp);
  }

  pagination.page = 1;
  conditions.value = condi;
}
const columnChange = () => {
  cloumnIndex();
  getList();
};

/**
 * 对数据进行监测，是否加载完毕，是否加载，并开始制作数据
 */
const doDataList = () => {
  loading.value = true;
  let start = new Date();
  let end = new Date();
  start.setHours(0);
  start.setMinutes(0);
  start.setSeconds(0);
  end.setHours(23);
  end.setMinutes(59);
  end.setSeconds(59);
  defaultTime2 = [start, end];
  getNameList()
    .then((res) => {
      options.value = res.data;
      let datas = {
        pageNum: pagination.page,
        pageSize: pagination.size,
        condition: JSON.stringify(conditions.value),
      };
      get(datas)
        .then((res) => {
          //获取到信息
          tableData.value = res.data.records;
          pagination.size = res.data.pageSize;
          pagination.page = res.data.currentPage;
          pagination.total = res.data.total;
          //请求完成,开始处理数据
          doEnterName();
          loading.value = false;
        })
        .catch((msg) => {
          //获取出错
          ElMessage.error("获取信息失败，请联系管理员！");
        });
        getUserRole();
    })
    .catch((msg) => { });
};
const doEnterName = () => {
  let tempTableData = tableData.value;
  let tempOptions = options.value;
  for (let i = 0; i < tempTableData.length; i++) {
    for (let j = 0; j < tempOptions.length; j++) {
      if (tempTableData[i].enterpriseCode === tempOptions[j].enterpriseCode) {
        tempTableData[i].enterName = tempOptions[j].cmpName;
      }
    }
  }
  tableData.value = tempTableData;
};
const updata = (index, rowData) => {
  eneryUpload(rowData)
    .then((res) => {
      if (res.status == 200) {
        ElMessage.success(res.message);
        doDataList();
      } else {
        ElMessage.error(JSON.stringify(res.data.responseMessage));
      }
    })
    .catch((msg) => {
      ElMessage.success(msg);
    });
};

//删除按钮触发
const deleteBtn=(id)=>{
  console.log(id)
    ElMessageBox.confirm(`确定进行删除操作?`,'提示',{
      confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
  }).then(()=>{
    logicDelete(id).then((res)=>{
      if (res.status == 200) {
        ElMessage.success(res.message);
        doDataList();
      } else {
        ElMessage.error(res.message);
      }
    })
  }).catch(() => {})
}

//批量删除
const deleteBatchBtn=()=>{
  var ids=selectChangeList.value.map((item)=>{
    return item.dataId
  })
  console.log(ids)
  ElMessageBox.confirm(`确定进行批量删除操作?`,'提示',{
      confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
  }).then(()=>{
    logicDeleteBatch(ids).then((res)=>{
      if (res.status == 200) {
        ElMessage.success(res.message);
        doDataList();
      } else {
        ElMessage.error(res.message);
      }
    })
  }).catch(() => {})
}

//批量上报
const uploadBatchBtn=()=>{
  var ids=selectChangeList.value.map((item)=>{
    return item.dataId
  })
  console.log(ids)
  ElMessageBox.confirm(`确定进行批量上报操作?`,'提示',{
      confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
  }).then(()=>{
    eneryUploadBatch(ids).then((res)=>{
      if (res.status == 200) {
        ElMessage.success(res.data);
        doDataList();
      } else {
        ElMessage.error(res.message);
      }
    })
  }).catch(() => {})
}

const stateDateSort = (a, b, c) => {
  cloumnIndex();
  let condi = conditions.value;
  if (a.order != null) {
    switch (a.order) {
      case "ascending":
        condi.push({
          column: a.prop,
          type: "orderBy",
          value: "asc",
        })
        break;

      case "descending":
        condi.push({
          column: a.prop,
          type: "orderBy",
          value: "desc",
        })
        break;
    }
  }
  doDataList();
}
// const filterHandler = (filters) => {
//   cloumnIndex();
//   let condi = conditions.value;
//   switch (filters.dataIndex[0]) {
//     case "1":
//       condi.push({
//         column: "dataIndex",
//         type: "en",
//         value: "",
//       })
//       break;
//     case "0":
//       condi.push({
//         column: "dataIndex",
//         type: "eq",
//         value: "",
//       })
//       break;
//   }
//   doDataList();
// }
getUserRole();
doDataList();
</script>

<style lang="less" scoped>
.title {
  min-width: 5em;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}



.pagination {
  max-height: 3vh;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
}

.total-font {
  margin-right: 15px;
  font-weight: 500;
  line-height: 21px;
  color: #595959;
}
</style>
